<template>
  <el-dialog
    :title="isEdit ? '编辑问题反馈' : '发布问题反馈'"
    v-model="dialogVisible"
    width="70%"
    :before-close="handleClose"
  >
    <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
      <div class="form-row">
        <el-form-item label="标题" prop="title" class="form-item">
          <el-input v-model="form.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        
        <el-form-item label="状态" prop="state" class="form-item">
          <el-select v-model="form.state" placeholder="请选择状态">
            <el-option
              v-for="option in stateOptions"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
      </div>

      <div class="form-row">
        <el-form-item label="站点" prop="siteId" class="form-item">
          <el-select v-model="form.siteId" placeholder="请选择站点">
            <el-option
              v-for="site in siteOptions"
              :key="site.id"
              :label="site.siteName"
              :value="site.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="机器编号" prop="equipmentId" class="form-item">
          <el-select v-model="form.equipmentId" placeholder="请选择机器编号">
            <el-option
              v-for="machine in machineOptions"
              :key="machine.id"
              :label="machine.equipmentName"
              :value="machine.id"
            />
          </el-select>
        </el-form-item>
      </div>

      <div class="form-row">

        <el-form-item label="部件" prop="componentId" class="form-item">
          <el-select v-model="form.componentId" placeholder="请选择部件">
            <el-option
              v-for="component in componentOptions"
              :key="component.id"
              :label="component.componentName"
              :value="component.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="模块" prop="moduleId" class="form-item">
          <el-select v-model="form.moduleId" placeholder="请选择模块">
            <el-option
              v-for="module in moduleOptions"
              :key="module.id"
              :label="module.moduleName"
              :value="module.id"
            />
          </el-select>
        </el-form-item>
      </div>

      <!-- <div class="form-row">
        <el-form-item label="类别" prop="categoryId" class="form-item">
          <el-select v-model="form.categoryId" placeholder="请选择类别">
            <el-option
              v-for="category in categoryOptions"
              :key="category.id"
              :label="category.categoryName"
              :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="责任所属" prop="responsibility" class="form-item">
          <el-select v-model="form.responsibility" placeholder="请选择责任人">
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="user.realname"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
      </div> -->

      <div class="form-row">
        <el-form-item label="发生时间" prop="happendTime" class="form-item">
          <el-date-picker
            v-model="form.happendTime"
            type="datetime"
            placeholder="选择发生时间"
            format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <!-- <el-form-item label="截止时间" prop="endTime" class="form-item">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择截止时间"
            format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item> -->
      </div>
      
      <el-form-item label="问题描述" prop="description">
        <RichTextEditor v-model="form.description" />
      </el-form-item>
      
      <el-form-item label="附件">
        <el-upload
          class="attachment-upload"
          :http-request="handleUploadRequest"
          :on-remove="handleFileRemove"
          :on-preview="handleFilePreview"
          :file-list="fileList"
          multiple
          :limit="6"
          list-type="text"
          :auto-upload="true"
          :disabled="isUploading"
          :before-upload="validateBeforeUpload"
        >
          <el-button type="primary" :disabled="isUploading">上传附件</el-button>
          <template #tip>
            <div class="el-upload__tip">支持多文件上传，单个文件不超过 10MB</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit"
          :disabled="isUploading"
        >确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, onMounted, nextTick } from 'vue'
import RichTextEditor from './RichTextEditor.vue'
import axios from '../plugins/axios'
import { ElMessage } from 'element-plus'

// 添加 isEdit 属性
const props = defineProps({
  visible: Boolean,
  editData: Object,
  isEdit: Boolean,  // 添加这一行
  siteOptions: Array,
  machineOptions: Array,
  categoryOptions: Array,
  moduleOptions: Array,
  componentOptions: Array
})

const emit = defineEmits(['update:visible', 'submit', 'refresh'])

const dialogVisible = ref(false)
const formRef = ref(null)
const userOptions = ref([])
const isUploading = ref(false)
const pendingUploads = ref(0)
const fileList = ref([])

const closeDialog = () => {
  dialogVisible.value = false
  emit('update:visible', false)
}

const handleClose = (done) => {
  closeDialog()
  if (typeof done === 'function') {
    done()
  }
}

// 处理提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    // 使用 editData 来判断是否是编辑状态
    const url = props.editData && Object.keys(props.editData).length > 0 ? '/daily/update' : '/daily/save'
    const response = await axios.post(url, form.value)
    if (response.data.code === 1) {
      ElMessage.success(props.editData && Object.keys(props.editData).length > 0  ? '修改成功' : '添加成功')
      closeDialog()
      emit('refresh')
    } else {
      ElMessage.error(response.data.msg || '操作失败')
    }
  } catch (error) {
    console.error('表单提交失败:', error)
    ElMessage.error('表单验证失败')
  }
}
const updateUploadingStatus = (isStart) => {
  pendingUploads.value += isStart ? 1 : -1
  if (pendingUploads.value < 0) pendingUploads.value = 0
  isUploading.value = pendingUploads.value > 0
}

const normalizeAttachmentPayload = (payload = {}) => ({
  id: payload.id ?? null,
  fileUrl: payload.fileUrl || payload.filePath || '',
  fileName: payload.fileName || payload.name || '',
  fileSize: payload.fileSize || null,
  mimeType: payload.mimeType || ''
})

const resolveAttachmentsFromEditData = (data = {}) => {
  if (Array.isArray(data.attachments) && data.attachments.length) {
    return data.attachments.map(normalizeAttachmentPayload)
  }
  if (data.attachment) {
    return [normalizeAttachmentPayload({ fileUrl: data.attachment, fileName: data.attachmentName })]
  }
  return []
}

const createDefaultForm = () => ({
  title: '',
  description: '',
  state: 1,
  siteId: '',
  equipmentId: '',
  categoryId: '',
  moduleId: '',
  componentId: '',
  happendTime: '',
  endTime: '',
  responsibility: '',
  attachments: []
})

const form = ref(createDefaultForm())

const syncFileListFromForm = () => {
  const list = form.value.attachments || []
  fileList.value = list.map((item, index) => ({
    name: item.fileName || `附件${index + 1}`,
    url: item.fileUrl,
    status: 'success',
    uid: `${item.id || item.fileUrl || index}`,
    id: item.id,
    size: item.fileSize || 0
  }))
}

const resetFormState = () => {
  form.value = createDefaultForm()
  fileList.value = []
}

// 状态选项
const stateOptions = [
  { id: 1, name: '未解决' },
  { id: 2, name: '进行中' },
  { id: 3, name: '已解决' },
  { id: 4, name: '已关闭' }
]

// 修改 watch editData 的处理
watch(
  () => props.editData,
  (newVal) => {
    if (newVal && Object.keys(newVal).length > 0) {
      nextTick(() => {
        form.value = {
          id: newVal.id,
          title: newVal.title,
          description: newVal.description || '',
          state: newVal.state,
          siteId: newVal.siteId || '',
          equipmentId: newVal.equipment?.id || '',
          categoryId: newVal.category?.id || '',
          moduleId: newVal.module?.id || '',
          componentId: newVal.component?.id || '',
          happendTime: newVal.happendTime ? newVal.happendTime.split('.')[0] : '',
          endTime: newVal.endTime ? newVal.endTime.split('.')[0] : '',
          responsibility: newVal.responsibility || '',
          attachments: resolveAttachmentsFromEditData(newVal)
        }
        syncFileListFromForm()
      })
    } else {
      resetFormState()
    }
  },
  { immediate: true }
)

// 修改 dialogVisible 的 watch
watch(dialogVisible, (val) => {
  emit('update:visible', val)
  if (!val) {
    nextTick(() => {
      formRef.value?.resetFields()
      resetFormState()
      pendingUploads.value = 0
      isUploading.value = false
    })
  }
})

// 获取用户列表
const fetchUsers = async () => {
  try {
    const response = await axios.get('/user/queryAll')  // 修改为正确的API地址
    if (response.data.code === 1) {
      userOptions.value = response.data.data
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  state: [{ required: true, message: '请选择状态', trigger: 'change' }],
  siteId: [{ required: true, message: '请选择站点', trigger: 'change' }],
  equipmentId: [{ required: true, message: '请选择机器编号', trigger: 'change' }],
  moduleId: [{ required: true, message: '请选择模块', trigger: 'change' }],
  componentId: [{ required: true, message: '请选择部件', trigger: 'change' }],
  happendTime: [{ required: true, message: '请选择发生时间', trigger: 'change' }],
  description: [{ required: true, message: '请输入问题描述', trigger: 'blur' }]
}

// 监听visible属性变化
watch(() => props.visible, (val) => {
  dialogVisible.value = val
  if (val) {
    fetchUsers() // 打开对话框时获取用户列表
  }
})

const validateBeforeUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 <= 10
  if (!isLt10M) {
    ElMessage.error('单个文件不能超过 10MB')
    return false
  }
  return true
}

const handleUploadRequest = async ({ file, onError }) => {
  updateUploadingStatus(true)
  const formData = new FormData()
  formData.append('file', file)
  try {
    const response = await axios.post('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    handleUploadSuccess(response.data, file)
  } catch (error) {
    handleUploadError()
    onError?.(error)
  } finally {
    updateUploadingStatus(false)
  }
}

const handleUploadSuccess = (response, rawFile) => {
  if (response?.code !== 1 || !response?.data) {
    ElMessage.error(response?.msg || '文件上传失败')
    return
  }
  const attachment = normalizeAttachmentPayload({
    ...response.data,
    fileName: response.data.fileName || rawFile?.name,
    fileSize: response.data.fileSize || rawFile?.size,
    mimeType: response.data.mimeType || rawFile?.type
  })
  form.value.attachments = [...(form.value.attachments || []), attachment]
  syncFileListFromForm()
  ElMessage.success('文件上传成功')
}

const handleUploadError = () => {
  ElMessage.error('文件上传失败')
}

const handleFileRemove = async (uploadFile) => {
  const list = form.value.attachments || []
  const targetIndex = list.findIndex((item) => item.fileUrl === uploadFile.url)
  if (targetIndex === -1) {
    return true
  }
  const target = list[targetIndex]
  if (target?.id) {
    try {
      const response = await axios.delete(`/feedback/file/${target.id}`)
      if (response.data.code !== 1) {
        ElMessage.error(response.data.msg || '删除附件失败')
        return false
      }
    } catch (error) {
      console.error('删除附件失败:', error)
      ElMessage.error('删除附件失败')
      return false
    }
  }
  list.splice(targetIndex, 1)
  form.value.attachments = [...list]
  syncFileListFromForm()
  ElMessage.success('附件已移除')
  return true
}

const handleFilePreview = (file) => {
  if (file?.url) {
    window.open(file.url, '_blank')
  }
}

// 选项数据
const siteOptions = ref([])
const machineOptions = ref([])
const componentOptions = ref([])
const categoryOptions = ref([])
const moduleOptions = ref([])

// 获取所有选项数据
const fetchOptions = async () => {
  try {
    // 获取站点选项
    const siteResponse = await axios.get('/site/queryAll')
    if (siteResponse.data.code === 1) {
      siteOptions.value = siteResponse.data.data
    }

    // 获取机器选项
    const machineResponse = await axios.get('/equipment-info/visible')
    if (machineResponse.data.code === 1) {
      machineOptions.value = machineResponse.data.data
    }

    // 获取部件选项
    const componentResponse = await axios.get('/component/queryAll')
    if (componentResponse.data.code === 1) {
      componentOptions.value = componentResponse.data.data
    }


    // 获取模块选项
    const moduleResponse = await axios.get('/module/queryAll')
    if (moduleResponse.data.code === 1) {
      moduleOptions.value = moduleResponse.data.data
    }
  } catch (error) {
    console.error('获取选项数据失败:', error)
    ElMessage.error('获取选项数据失败')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchUsers()
  fetchOptions()
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-select),
:deep(.el-date-picker) {
  width: 100%;
}

/* 富文本编辑器和附件上传占满整行 */
:deep(.el-form-item.form-item) {
  margin: 0;
}

.attachment-upload {
  width: 100%;
}
</style>
